/**
 * 商品管理
 */
package com.zhaogang.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import com.zhaogang.dto.GoodsDto;
import com.zhaogang.dto.SaleGoodsDetailDTO;
import com.zhaogang.entity.Goods;
import com.zhaogang.entity.Order;
import com.zhaogang.entity.Page;
import com.zhaogang.entity.SaleAccount;
import com.zhaogang.entity.SaleGoods;
import com.zhaogang.entity.UserAccount;
import com.zhaogang.entity.UserDetails;
import com.zhaogang.service.GoodsService;
import com.zhaogang.service.OrderService;
import com.zhaogang.service.UserDetailsService;

/**
 * 
 * @author xiao.shu 2017年4月21日 下午1:03:45
 */

@Controller
@RequestMapping(value = "/goods")
public class GoodsController {

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private UserDetailsService userDetailsService;

	
			//模糊查询
			@RequestMapping(value="/specialQuery")
			@ResponseBody
			public List<SaleGoodsDetailDTO> specialQuery(String keyword, HttpServletRequest request){
				System.out.println(keyword);
				List<SaleGoodsDetailDTO> list = goodsService.queryListForShow(keyword);	
				System.out.println(list);
				return list;
			}
			
			//首页进入的全部查询
			@RequestMapping(value="/firstQuery")
			public String firstQuery(){
				return "redirect:/goods/specialShow";
			}
			
			
			/*
			 * 商城首页查询读取，若视图无法解析，则清空session，重新进行解析！
			 */
			@RequestMapping(value="/specialShow")
			public ModelAndView specialShow(HttpServletRequest request){
				ModelAndView view = new ModelAndView("user/productList");
				List<SaleGoodsDetailDTO> list = goodsService.specialQuery();
				System.out.println("list:"+list);
				view.addObject("specialShow", list);
				try {
					return view;
				} catch (Exception e) {
					HttpSession session = request.getSession();
					session.removeAttribute("userToken");
					view.setViewName("user/productList");
					return view;
				}
			}

	// ---------------------------结束--------------------//

	/**
	 * 商品详情页
	 * 
	 * @param id
	 *            商品id
	 * @return
	 * @time 上午9:53:47
	 */
	@RequestMapping("/detail")
	public ModelAndView list(String id) {
		ModelAndView mv= new  ModelAndView();
		int goodsid ;
		try{
			goodsid = Integer.parseInt(id);
		}catch(Exception e){
			mv.setViewName("redirect:/goods/firstQuery");
			return  mv;
		}
		
		SaleGoods saleGoods = goodsService.queryBysale_goodsId(goodsid);	
		if(saleGoods == null){
			mv.setViewName("redirect:/goods/firstQuery");
			return  mv;
		}
		
		Goods goods = goodsService.queryGoodsByGoodsId(Integer.parseInt(saleGoods.getGoodsId()));
		if(goods == null ){
			mv.setViewName("redirect:/goods/firstQuery");
			return  mv;
		}		
		// System.out.println(saleGoods);		
		// System.out.println(goods);
		mv.setViewName("user/goodsDetail");
		mv.addObject("sale_goods_id", id);
		mv.addObject("goods", goods);
		mv.addObject("saleGoods", saleGoods);
		return mv;
	}

	@RequestMapping("/buy1")
	public ModelAndView buy(Goods order) throws Exception {
		System.out.println(order);
		return null;
	}
	
	@RequestMapping("/buy")
	public void buy2(HttpServletRequest request,HttpServletResponse response) throws Exception{
		UserAccount userAccount = (UserAccount) request.getSession().getAttribute("userToken");
		System.out.println(userAccount);
		//判断是否为空 为空表明没有登录，跳到登录界面
		//否则继续往下进行
		if(userAccount == null){
			//String redirUrl = request.get
			System.out.println("redirUrl:"+request.getHeader("referer"));
			response.sendRedirect("../user/login?redirUrl="+request.getHeader("referer"));
		}else{
			request.getRequestDispatcher("/order/showOrder").forward(request, response);
		}		
	}

	
	//点击购买按钮跳转到此方法
		@RequestMapping("/buy3")
		public ModelAndView buy1(HttpServletRequest request) throws Exception{
			
			ModelAndView mv=null;
			
			//从session中得到用户账户对象
			UserAccount userAccount = (UserAccount) request.getSession().getAttribute("userToken");
			System.out.println(userAccount);
			//判断是否为空 为空表明没有登录，跳到登录界面
			//否则继续往下进行
			if(userAccount == null){
				//String redirUrl = request.get
				System.out.println("redirUrl:"+request.getHeader("referer"));
				mv = new ModelAndView("redirect:/pages/user/login.jsp?redirUrl="+request.getHeader("referer"));
				return mv;
			}
			System.out.println(userAccount);
			
			//获取详情页面的购买参数
			request.setCharacterEncoding("utf-8");
			int userSum = Integer.parseInt(request.getParameter("userSum"));
			Integer saleGoodsId = Integer.parseInt(request.getParameter("id"));
			double single_price = Double.valueOf(request.getParameter("single_price"));
			//组装order对象
			//得到某一账号的用户详情对象
			UserDetails userDetails = userDetailsService.queryUserDetailByuserAccount(userAccount.getId());
			
			System.out.println("userDetails:"+userDetails);
			Order order = new Order();				
			if(userDetails != null){			
				order.setRecAddress(userDetails.getAddress());
				order.setRecPhone(userDetails.getPhone());
				order.setRecName(userDetails.getRealname());
			}else{
				order.setRecAddress("湖北省武汉市");
				order.setRecPhone("15827598200");
				order.setRecName("王康");
			}
			
			order.setUserAccountId(userAccount.getId());		
			order.setSaleGoodsId(saleGoodsId);
			order.setSinglePrice(single_price);
			order.setNum(userSum);
			order.setSumPrice(userSum*single_price);
			order.setOrderTime(new Date());		
			
			//订单生成与否，界面的跳转
			if(orderService.AddOrder(order)){
				//System.out.println("success");
				mv = new ModelAndView("redirect:../order/showOrder?id="+order.getId());		
			}else{
				//System.out.println("error");
				mv = new ModelAndView("redirect:../goods/detail?id="+saleGoodsId);
			}
			return mv;
		}

	/**
	 * 查询所有的
	 * 
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/goods", method = RequestMethod.GET)

	public String goods(Model model, HttpServletRequest request, Page page) {

		HttpSession session = request.getSession();
		SaleAccount saleToken = (SaleAccount) session.getAttribute("saleToken");
		System.out.println(saleToken);
		try {
			String saleAccount = saleToken.getSaleAccount();
			model.addAttribute("saleAccount", saleAccount);
			Page p = goodsService.findpage(saleAccount, page);
			System.out.println(p);
			page.setTotalCount(p.getTotalCount());
			page.setTotalPageCount(p.getTotalPageCount());
			List<GoodsDto> list = goodsService.queryList(saleAccount, p);
			System.out.println(list);
			model.addAttribute("list", list);
		} catch (Exception e) {
			System.out.println("未登录，没有session");
		}
		return "goods/goods";
	}

	/**
	 * 增加
	 * 
	 * @return
	 */

	@RequestMapping(value = "/toAdd", method = RequestMethod.GET)
	public String addPage(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		SaleAccount saleToken = (SaleAccount) session.getAttribute("saleToken");

		try {
			String saleAccount = saleToken.getSaleAccount();
			model.addAttribute("saleAccount",saleAccount);
			
			Integer i = goodsService.queryState(saleAccount);
			 if(i==null){
				 JOptionPane.showMessageDialog(null, "即将跳往入驻页面","您还未申请入驻", JOptionPane.ERROR_MESSAGE);
				 return "redirect:/sale/infoShow";
			 }
			model.addAttribute("i", i);
		} catch (Exception e) {
			System.out.println("未得到session");
		}

		return "goods/insertGoods";

	}

	/**
	 * 添加 
	 * @param goods
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public String save(GoodsDto goodsDto, @RequestParam(value = "iconFile") MultipartFile file,
			HttpServletRequest request, Model model) throws IOException {

		HttpSession session1 = request.getSession();
		SaleAccount saleToken = (SaleAccount) session1.getAttribute("saleToken");
		try {
			String saleAccount = saleToken.getSaleAccount();
		model.addAttribute("saleAccount", saleAccount);
		goodsDto.setSaleAccount(saleAccount);
			
		} catch (Exception e) {
			System.out.println("添加时未取得session");
		}
		if (file.getInputStream() != null)
			;
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		String path = context.getRealPath("/");
		path = path + "images";
		InputStream is = null;
		FileOutputStream fos = null;
		String path1 = UUID.randomUUID().toString()+".jpg";
		try {
			fos = new FileOutputStream(new File(path + File.separator + path1));
			is = file.getInputStream();
			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = is.read(buffer)) != -1) {
				fos.write(buffer, 0, count);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			goodsDto.setIcon(path1);// 存图片不能再写uuid
		}
		goodsService.insertObject(goodsDto);

		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/goods/goods";
	}
	/*@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public String save(GoodsDto goodsDto, @RequestParam(value = "iconFile") MultipartFile file,
			HttpServletRequest request, Model model) throws IOException {

		HttpSession session1 = request.getSession();
		SaleAccount saleToken = (SaleAccount) session1.getAttribute("saleToken");
		try {
			String saleAccount = saleToken.getSaleAccount();
		model.addAttribute("saleAccount", saleAccount);
		goodsDto.setSaleAccount(saleAccount);
			
		} catch (Exception e) {
			System.out.println("添加时未取得session");
		}
		if (file.getInputStream() != null)
			;
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		String path = context.getRealPath("/");
		path = path + "images";
		InputStream is = null;
		FileOutputStream fos = null;
		String path1 = UUID.randomUUID().toString()+".jpg";
		try {
			fos = new FileOutputStream(new File(path + File.separator + path1));
			is = file.getInputStream();
			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = is.read(buffer)) != -1) {
				fos.write(buffer, 0, count);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			goodsDto.setIcon(path + File.separator + path1);// 存图片不能再写uuid
		}
		goodsService.insertObject(goodsDto);

		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/goods/goods";
	}*/

	/**
	 * 修改时回显
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/toUpdate", method = RequestMethod.GET)
	public String queryObject(Integer id, HttpServletRequest request, Model model) {

		HttpSession session = request.getSession();
		SaleAccount saleToken = (SaleAccount) session.getAttribute("saleToken");
		try {String saleAccount = saleToken.getSaleAccount();
		model.addAttribute("saleAccount", saleAccount);
		GoodsDto goodsDto = goodsService.queryObject(id, saleAccount);
		model.addAttribute("em", goodsDto);
			
		} catch (Exception e) {
			System.out.println("未取到session");
		}
		
		return "goods/updateGoods";
	}

	/**
	 * 修改
	 * 
	 * @param goods
	 * @return
	 */
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String save1(GoodsDto goodsDto, @RequestParam(value = "iconFile") MultipartFile file,
			HttpServletRequest request, Model model) {

		HttpSession session1 = request.getSession();
		SaleAccount saleToken = (SaleAccount) session1.getAttribute("saleToken");
		try {
			String saleAccount = saleToken.getSaleAccount();
			model.addAttribute("saleAccount", saleAccount);
			goodsDto.setSaleAccount(saleAccount);
		} catch (Exception e) {
			System.out.println("修改时未获得session");
		}
		
		try {
			if (file.getInputStream() != null)
				;
		} catch (IOException e1) {

			e1.printStackTrace();
		}
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		
		String path = context.getRealPath("/");
		path = path + "images";
		InputStream is = null;
		FileOutputStream fos = null;
		if (file.isEmpty()) {
			String path1 = null;
			goodsDto.setIcon(path1);
		} else {
			String path1 = UUID.randomUUID().toString()+".jpg";
			try {
				fos = new FileOutputStream(new File(path + File.separator + path1));
				is = file.getInputStream();
				byte[] buffer = new byte[1024];
				int count = 0;
				while ((count = is.read(buffer)) != -1) {
					fos.write(buffer, 0, count);
				}
			}

			catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			goodsDto.setIcon(path1);
		}
		goodsService.updateObject(goodsDto);
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/goods/goods";
	}
	
	/*@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String save1(GoodsDto goodsDto, @RequestParam(value = "iconFile") MultipartFile file,
			HttpServletRequest request, Model model) {

		HttpSession session1 = request.getSession();
		SaleAccount saleToken = (SaleAccount) session1.getAttribute("saleToken");
		try {
			String saleAccount = saleToken.getSaleAccount();
			model.addAttribute("saleAccount", saleAccount);
			goodsDto.setSaleAccount(saleAccount);
		} catch (Exception e) {
			System.out.println("修改时未获得session");
		}
		
		try {
			if (file.getInputStream() != null)
				;
		} catch (IOException e1) {

			e1.printStackTrace();
		}
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		String path = context.getRealPath("/");
		path = path + "images";
		InputStream is = null;
		FileOutputStream fos = null;
		if (file.isEmpty()) {
			String path1 = null;
			goodsDto.setIcon(path1);
		} else {
			String path1 = UUID.randomUUID().toString()+".jpg";
			try {
				fos = new FileOutputStream(new File(path + File.separator + path1));
				is = file.getInputStream();
				byte[] buffer = new byte[1024];
				int count = 0;
				while ((count = is.read(buffer)) != -1) {
					fos.write(buffer, 0, count);
				}
			}

			catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			goodsDto.setIcon(path1);
		}
		goodsService.updateObject(goodsDto);
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/goods/goods";
	}*/

	/**
	 * 删除 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String deleteObject(GoodsDto goodsDto, HttpServletRequest request) {

		HttpSession session = request.getSession();
		SaleAccount saleToken = (SaleAccount) session.getAttribute("saleToken");
		try {
			String saleAccount = saleToken.getSaleAccount();
			goodsDto.setSaleAccount(saleAccount);
		} catch (Exception e) {
		System.out.println("删除时未得到session");	
		}
		goodsService.deleteObject(goodsDto);
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + "/goods/goods";
	}

	/**
	 * 条件查询
	 * 
	 * @param id
	 * @param goodsName
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/queryByCon", method = { RequestMethod.POST, RequestMethod.GET })
	public Object queryByCon(@RequestParam(value = "id", required = false) Integer id,
			@RequestParam(value = "goodsName", required = false) String goodsName, HttpServletRequest request,
			Model model) {

		try {
			String goodsName1 = new String(request.getParameter("goodsName").getBytes("ISO8859-1"), "utf-8");
			model.addAttribute("listid", id);
			model.addAttribute("listname", goodsName1);

			HttpSession session = request.getSession();
			SaleAccount saleToken = (SaleAccount) session.getAttribute("saleToken");
			String saleAccount = saleToken.getSaleAccount();
			GoodsDto goodsDto = new GoodsDto();
			goodsDto.setId(id);
			goodsDto.setGoodsName(goodsName1);
			goodsDto.setSaleAccount(saleAccount);
			List<Goods> list = goodsService.queryByCon(goodsDto);

			model.addAttribute("list", list);
		} catch (Exception e) {

			System.out.println("未登录，没有session");
		}
		return "goods/goods";

	}
}
